package com.peng.leetcode.search;

/**
 * SearchMatrix
 * 74. 搜索二维矩阵
 * https://leetcode.cn/problems/search-a-2d-matrix/
 * <p>
 * Created on 2022/12/10
 *
 * @author lupeng
 */
public class SearchMatrix {
    public boolean searchMatrix(int[][] matrix, int target) {
        for (int[] arr : matrix) {
            if (arr[0] <= target && target <= arr[arr.length - 1]) {
                int index = binarySearch(arr, target);
                if (index < arr.length && arr[index] == target) {
                    return true;
                }
            }
        }
        return false;
    }

    int binarySearch(int[] arr, int target) {
        int l = 0, r = arr.length;
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (arr[mid] < target) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        return l;
    }
}
